package com.dingshi.security;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.dingshi.security.api.ApiResult;
import com.dingshi.security.api.ApiReturnResultListener;
import com.dingshi.security.api.UserApi;
import com.dingshi.security.util.Utils;
import com.dingshi.security.view.LoadDialog;

public class WelcomeActivity extends Activity {

	private static final int ID_LOADING = 2012;
	private DataLoaderTask task;
	private ProgressBar mProgressBar;
	private boolean login = true;
	private LocationManager locationManager;
	private TextView load_text;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.startup);
		load_text = (TextView)findViewById(R.id.load_text);
		mProgressBar = (ProgressBar)findViewById(R.id.progressBar);
		mProgressBar.setVisibility(View.INVISIBLE);
		load_text.setVisibility(View.INVISIBLE);
		mProgressBar.setMax(100);
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		
		if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS ); 
			startActivityForResult(myIntent, 1);
		}else {
			auth();
		}
		
	}
	
	private void auth() {
		UserApi api = new UserApi(this);
		api.setReturnResultListener(new ApiReturnResultListener() {
			
			@Override
			public <T> void onReturnSucceedResult(int requestCode,
					ApiResult<T> apiResult) {
				dismissDialog(ID_LOADING);
				if(ApiResult.RESULT_OK==apiResult.getResultCode()) {
					JSONObject jsonEntity = apiResult.getJsonEntity();
					//{"d":{"__type":"AuthorizationReturn:r","d":"成功！","s":"1"},"t":0}

					if(jsonEntity!=null) {
						try {
							int type = jsonEntity.getInt("t");
							switch (type) {
							case 0:// 对象
								Utils.showToast(WelcomeActivity.this, "验证成功");
								JSONObject obj = jsonEntity.getJSONObject("d");
								if("1".equals(obj.getString("s"))) {
									if (task != null) {
										task.cancel(true);
										task = null;
									}
									task = new DataLoaderTask();
									task.execute();	
								}
								break;
							case 1:// 数组
								break;
							case -1:// 错误
								Utils.showToast(WelcomeActivity.this, "验证失败");
								break;

							default:
								break;
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}else {
						Utils.showToast(WelcomeActivity.this, "验证失败");
					}
				}
			}
			
			@Override
			public <T> void onReturnLoading(int requestCode) {
				showDialog(ID_LOADING);
			}
			
			@Override
			public <T> void onReturnFailResult(int requestCode, ApiResult<T> apiResult) {
				dismissDialog(ID_LOADING);
				Utils.showToast(WelcomeActivity.this, "验证失败");
			}
		});
		api.auth(1, this, Utils.getDeviceId(this));
		
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case ID_LOADING:
			LoadDialog dialog = new LoadDialog(this, "帐号验证中...");
			return dialog;

		default:
			break;
		}
		return super.onCreateDialog(id);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){  
			finish();
		}else {
			SecurityApp.getApp(this).initGpsLocation();
			if (task != null) {
				task.cancel(true);
				task = null;
			}
			task = new DataLoaderTask();
			task.execute();
		}
		super.onActivityResult(requestCode, resultCode, data);
		
	}

	class DataLoaderTask extends AsyncTask<Void, Integer, Long> {

		@Override
		protected Long doInBackground(Void... arg0) {
			
			for(int i=0;i<100;i++) {
				try {
					Thread.sleep(10);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				publishProgress(i);
			}
			return null;
		}
		
		

		@Override
		protected void onProgressUpdate(Integer... values) {
			mProgressBar.setProgress(values[0]);
			super.onProgressUpdate(values);
		}



		@Override
		protected void onPostExecute(Long result) {
			Intent intent = null;
			if(!login ) {
				intent = new Intent(WelcomeActivity.this,HomeActivity.class);
				startActivity(intent);
			}else {
				intent = new Intent(WelcomeActivity.this,LoginActivity.class);
				startActivity(intent);
			}
			
			finish();
			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			mProgressBar.setVisibility(View.VISIBLE);
			load_text.setVisibility(View.VISIBLE);
			task = null;
			super.onPreExecute();
		}

	}
}